<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件上传与留言板系统</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1000px;
            margin: 0 auto;
            padding: 20px;
            line-height: 1.6;
        }

        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 30px;
        }

        .container {
            display: flex;
            gap: 20px;
        }

        .section {
            flex: 1;
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 20px;
            background-color: #f9f9f9;
        }

        .section-title {
            margin-top: 0;
            color: #444;
            border-bottom: 1px solid #ddd;
            padding-bottom: 10px;
        }

        /* 文件上传部分样式 */
        .upload-container {
            border: 2px dashed #ccc;
            border-radius: 5px;
            padding: 20px;
            text-align: center;
            margin: 15px 0;
        }

        .upload-container:hover {
            border-color: #999;
        }

        #file-input {
            display: none;
        }

        .upload-btn {
            background-color: #4CAF50;
            color: white;
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }

        .upload-btn:hover {
            background-color: #45a049;
        }

        #file-info {
            margin-top: 10px;
            font-size: 14px;
        }

        #submit-btn {
            background-color: #2196F3;
            color: white;
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            display: block;
            margin: 15px auto;
        }

        #submit-btn:hover {
            background-color: #0b7dda;
        }

        #submit-btn:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }

        /* 留言板部分样式 */
        #message-form {
            margin-top: 20px;
        }

        #message-input {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            resize: vertical;
            min-height: 80px;
            margin-bottom: 10px;
        }

        #submit-message {
            background-color: #ff9800;
            color: white;
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }

        #submit-message:hover {
            background-color: #e68a00;
        }

        #messages-container {
            margin-top: 20px;
            max-height: 400px;
            overflow-y: auto;
        }

        .message {
            background-color: white;
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 12px;
            margin-bottom: 10px;
            position: relative;
        }

        .message-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
            font-size: 14px;
        }

        .message-author {
            font-weight: bold;
            color: #2196F3;
        }

        .message-time {
            color: #777;
            font-size: 12px;
        }

        .message-content {
            word-wrap: break-word;
        }

        /* 进度条和通知样式 */
        .progress-container {
            width: 100%;
            background-color: #ddd;
            border-radius: 5px;
            margin: 15px 0;
            display: none;
        }

        #progress-bar {
            width: 0%;
            height: 20px;
            background-color: #4CAF50;
            border-radius: 5px;
            text-align: center;
            line-height: 20px;
            color: white;
            font-size: 12px;
        }

        .notification {
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
            display: none;
        }

        .success {
            background-color: #dff0d8;
            color: #3c763d;
            border: 1px solid #d6e9c6;
        }

        .error {
            background-color: #f2dede;
            color: #a94442;
            border: 1px solid #ebccd1;
        }

        .delete-btn {
            background-color: #f44336;
            color: white;
            border: none;
            border-radius: 3px;
            padding: 3px 8px;
            font-size: 12px;
            cursor: pointer;
            float: right;
            margin-top: -25px;
        }

        .delete-btn:hover {
            background-color: #d32f2f;
        }

        /* 批量操作按钮样式 */
        .message-actions {
            margin-bottom: 10px;
        }

        .message-actions button {
            background-color: #f5f5f5;
            border: 1px solid #ddd;
            border-radius: 3px;
            padding: 5px 10px;
            margin-right: 5px;
            cursor: pointer;
        }

        .message-actions button:hover {
            background-color: #eaeaea;
        }

        .message-actions button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        /* 留言选择框样式 */
        .message-checkbox {
            margin-right: 10px;
        }

        /* 文件列表样式 */
        .file-list-container {
            margin-top: 20px;
            border-top: 1px solid #ddd;
            padding-top: 15px;
        }

        .file-list {
            max-height: 300px;
            overflow-y: auto;
        }

        .file-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 10px;
            border-bottom: 1px solid #eee;
            cursor: pointer;
        }

        .file-item:hover {
            background-color: #f5f5f5;
        }

        .file-name {
            flex: 1;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .file-size {
            color: #777;
            font-size: 12px;
            margin-left: 10px;
        }

        .file-date {
            color: #999;
            font-size: 12px;
            margin-left: 10px;
        }
    </style>
</head>

<body>
    <h1>文件上传与留言板系统</h1>

    <div class="container">
        <!-- 文件上传部分 -->
        <div class="section">
            <h2 class="section-title">文件上传</h2>

            <form id="upload-form" action="/upload" method="post" enctype="multipart/form-data">
                <div class="upload-container">
                    <label for="file-input">
                        <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="#ccc" stroke-width="2"
                            stroke-linecap="round" stroke-linejoin="round">
                            <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
                            <polyline points="17 8 12 3 7 8"></polyline>
                            <line x1="12" y1="3" x2="12" y2="15"></line>
                        </svg>
                        <p>点击或拖拽文件到此处上传</p>
                        <button type="button" class="upload-btn">选择文件</button>
                        <input type="file" id="file-input" name="file" multiple>
                    </label>
                    <div id="file-info"></div>
                </div>

                <div class="progress-container" id="progress-container">
                    <div id="progress-bar">0%</div>
                </div>

                <button type="submit" id="submit-btn" disabled>上传文件</button>
            </form>

            <div id="upload-notification" class="notification"></div>

            <div class="file-list-container">
                <h3>已上传文件</h3>
                <div id="file-list">
                    <!-- 文件列表将通过JavaScript动态插入到这里 -->
                </div>
            </div>
        </div>

        <!-- 留言板部分 -->
        <div class="section">
            <h2 class="section-title">留言板</h2>

            <form id="message-form">
                <textarea id="message-input" placeholder="请输入您的留言..." required></textarea>
                <button type="submit" id="submit-message">发布留言</button>

            </form>
            <!-- 在留言板部分的HTML中添加批量操作按钮 -->
            <div class="message-actions">
                <button id="select-all-btn">全选</button>
                <button id="batch-delete-btn" disabled>删除选中</button>
            </div>
            <div id="messages-container"></div>

            <div id="message-notification" class="notification"></div>
        </div>
    </div>


    <script>
        // 文件上传功能
        const fileInput = document.getElementById('file-input');
        const fileInfo = document.getElementById('file-info');
        const submitBtn = document.getElementById('submit-btn');
        const uploadForm = document.getElementById('upload-form');
        const progressContainer = document.getElementById('progress-container');
        const progressBar = document.getElementById('progress-bar');
        const uploadNotification = document.getElementById('upload-notification');

        // 留言板功能
        const messageForm = document.getElementById('message-form');
        const messageInput = document.getElementById('message-input');
        const messagesContainer = document.getElementById('messages-container');
        const messageNotification = document.getElementById('message-notification');

        // 初始化 - 加载现有留言
        document.addEventListener('DOMContentLoaded', loadMessages);

        // 文件上传功能
        document.querySelector('.upload-btn').addEventListener('click', function (e) {
            e.preventDefault();
            fileInput.click();
        });

        const uploadContainer = document.querySelector('.upload-container');

        uploadContainer.addEventListener('dragover', function (e) {
            e.preventDefault();
            this.style.borderColor = '#4CAF50';
        });

        uploadContainer.addEventListener('dragleave', function () {
            this.style.borderColor = '#ccc';
        });

        uploadContainer.addEventListener('drop', function (e) {
            e.preventDefault();
            this.style.borderColor = '#ccc';

            if (e.dataTransfer.files.length) {
                fileInput.files = e.dataTransfer.files;
                updateFileInfo();
            }
        });

        fileInput.addEventListener('change', updateFileInfo);

        function updateFileInfo() {
            if (fileInput.files.length > 0) {
                let fileNames = [];
                let totalSize = 0;

                for (let i = 0; i < fileInput.files.length; i++) {
                    fileNames.push(fileInput.files[i].name);
                    totalSize += fileInput.files[i].size;
                }

                const sizeInMB = (totalSize / (1024 * 1024)).toFixed(2);

                fileInfo.innerHTML = `
                    <strong>已选择 ${fileInput.files.length} 个文件:</strong><br>
                    ${fileNames.join('<br>')}<br>
                    <strong>总大小:</strong> ${sizeInMB} MB
                `;

                submitBtn.disabled = false;
            } else {
                fileInfo.textContent = '';
                submitBtn.disabled = true;
            }
        }



        uploadForm.addEventListener('submit', function (e) {
            e.preventDefault();

            // 禁用提交按钮防止重复提交
            const submitBtn = document.getElementById('submit-btn');
            submitBtn.disabled = true;
            const originalBtnText = submitBtn.textContent;
            submitBtn.textContent = '上传中...';

            const formData = new FormData(this);
            const xhr = new XMLHttpRequest();

            progressContainer.style.display = 'block';
            uploadNotification.style.display = 'none';

            // 上传进度处理
            xhr.upload.addEventListener('progress', function (e) {
                if (e.lengthComputable) {
                    const percent = Math.round((e.loaded / e.total) * 100);
                    progressBar.style.width = percent + '%';
                    progressBar.textContent = percent + '%';
                }
            });

            // 上传完成处理
            xhr.addEventListener('load', function () {
                // 恢复按钮状态
                submitBtn.disabled = false;
                submitBtn.textContent = originalBtnText;

                try {
                    const response = JSON.parse(xhr.responseText);
                    if (xhr.status === 200) {
                        showNotification(uploadNotification, response.message || '文件上传成功!', 'success');
                        loadFileList(); // 上传成功后刷新文件列表
                    } else {
                        showNotification(uploadNotification, response.error || '上传过程中出现错误', 'error');
                    }
                } catch (e) {
                    showNotification(uploadNotification, '文件上传完成，但服务器响应异常', 'error');
                }

                // 重置进度条和表单
                setTimeout(() => {
                    progressContainer.style.display = 'none';
                    progressBar.style.width = '0%';
                    progressBar.textContent = '0%';
                    fileInput.value = '';
                    updateFileInfo();
                }, 2000);
            });

            // 上传错误处理
            xhr.addEventListener('error', function () {
                submitBtn.disabled = false;
                submitBtn.textContent = originalBtnText;
                showNotification(uploadNotification, '上传过程中发生错误', 'error');
                progressContainer.style.display = 'none';
            });

            // 上传中止处理
            xhr.addEventListener('abort', function () {
                submitBtn.disabled = false;
                submitBtn.textContent = originalBtnText;
                showNotification(uploadNotification, '上传已取消', 'error');
                progressContainer.style.display = 'none';
            });

            xhr.open('POST', this.action, true);
            xhr.send(formData);
        });


        function showNotification(element, message, type) {
            element.textContent = message;
            element.className = 'notification ' + type;
            element.style.display = 'block';

            setTimeout(() => {
                element.style.display = 'none';
            }, 3000);
        }




        // 加载现有留言
        function loadMessages() {
            fetch('/messages')
                .then(response => response.json())
                .then(messages => {
                    displayMessages(messages);
                })
                .catch(error => {
                    console.error('获取留言失败:', error);
                    showNotification(messageNotification, '加载留言失败', 'error');
                });
        }

        // 显示留言到页面
        function displayMessages(messages) {
            const container = document.getElementById('messages-container');
            container.innerHTML = '';

            if (messages.length === 0) {
                container.innerHTML = '<p>暂无留言</p>';
                return;
            }

            messages.forEach(msg => {
                const messageElement = document.createElement('div');
                messageElement.className = 'message';
                messageElement.dataset.id = msg.id; // 存储留言ID

                const time = new Date(msg.timestamp).toLocaleString();

                messageElement.innerHTML = `
            <div class="message-header">
                <span class="message-author">${msg.author || '匿名用户'}</span>
                <span class="message-time">${time}</span>
            </div>
            <div class="message-content">${msg.content}</div>
            <button class="delete-btn" data-id="${msg.id}">删除</button>
        `;
                container.appendChild(messageElement);
            });

            // 添加删除按钮事件监听
            document.querySelectorAll('.delete-btn').forEach(btn => {
                btn.addEventListener('click', deleteMessage);
            });
        }

        // 页面加载时获取留言
        document.addEventListener('DOMContentLoaded', loadMessages);


        // 删除留言函数
        function deleteMessage(event) {
            const messageId = event.target.dataset.id;

            if (confirm('确定要删除这条留言吗？')) {
                fetch(`/message/${messageId}`, {
                        method: 'DELETE'
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            showNotification(messageNotification, '留言已删除', 'success');
                            loadMessages(); // 刷新留言列表
                        } else {
                            showNotification(messageNotification, data.error || '删除失败', 'error');
                        }
                    })
                    .catch(error => {
                        console.error('删除留言失败:', error);
                        showNotification(messageNotification, '删除留言时出错', 'error');
                    });
            }
        }


        let isSubmitting = false;

        document.getElementById('message-form').addEventListener('submit', function (e) {
            e.preventDefault();

            if (isSubmitting) return;
            isSubmitting = true;

            const content = document.getElementById('message-input').value.trim();
            const submitBtn = document.getElementById('submit-message');
            const originalText = submitBtn.textContent;

            submitBtn.textContent = '发布中...';
            submitBtn.disabled = true;

            fetch('/message', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        content
                    })
                })
                .then(response => {
                    if (!response.ok) throw new Error('网络响应异常');
                    return response.json();
                })
                .then(data => {
                    document.getElementById('message-input').value = '';
                    loadMessages();
                    showNotification(messageNotification, '留言发布成功!', 'success');
                })
                .catch(error => {
                    console.error('提交留言失败:', error);
                    showNotification(messageNotification, '留言发布失败', 'error');
                })
                .finally(() => {
                    isSubmitting = false;
                    submitBtn.textContent = originalText;
                    submitBtn.disabled = false;
                });
        });


        // 在displayMessages函数中添加选择框
        function displayMessages(messages) {
            const container = document.getElementById('messages-container');
            container.innerHTML = '';

            if (messages.length === 0) {
                container.innerHTML = '<p>暂无留言</p>';
                return;
            }

            messages.forEach(msg => {
                const messageElement = document.createElement('div');
                messageElement.className = 'message';
                messageElement.dataset.id = msg.id;

                const time = new Date(msg.timestamp).toLocaleString();

                messageElement.innerHTML = `
            <div class="message-header">
                <input type="checkbox" class="message-checkbox" data-id="${msg.id}">
                <span class="message-author">${msg.author || '匿名用户'}</span>
                <span class="message-time">${time}</span>
            </div>
            <div class="message-content">${msg.content}</div>
            <button class="delete-btn" data-id="${msg.id}">删除</button>
        `;
                container.appendChild(messageElement);
            });

            // 添加删除按钮事件监听
            document.querySelectorAll('.delete-btn').forEach(btn => {
                btn.addEventListener('click', deleteMessage);
            });

            // 添加复选框事件监听
            document.querySelectorAll('.message-checkbox').forEach(checkbox => {
                checkbox.addEventListener('change', updateBatchDeleteButton);
            });
        }

        // 更新批量删除按钮状态
        function updateBatchDeleteButton() {
            const checkedBoxes = document.querySelectorAll('.message-checkbox:checked');
            const batchDeleteBtn = document.getElementById('batch-delete-btn');
            batchDeleteBtn.disabled = checkedBoxes.length === 0;
        }

        // 全选功能
        document.getElementById('select-all-btn').addEventListener('click', function () {
            const checkboxes = document.querySelectorAll('.message-checkbox');
            const allChecked = Array.from(checkboxes).every(checkbox => checkbox.checked);

            checkboxes.forEach(checkbox => {
                checkbox.checked = !allChecked;
            });

            updateBatchDeleteButton();
        });

        // 批量删除功能
        document.getElementById('batch-delete-btn').addEventListener('click', function () {
            const checkedBoxes = document.querySelectorAll('.message-checkbox:checked');
            if (checkedBoxes.length === 0) return;

            const ids = Array.from(checkedBoxes).map(checkbox =>
                parseInt(checkbox.dataset.id)
            );

            if (confirm(`确定要删除选中的 ${ids.length} 条留言吗？`)) {
                fetch('/messages/batch', {
                        method: 'DELETE',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            ids
                        })
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            showNotification(messageNotification, data.message, 'success');
                            loadMessages(); // 刷新留言列表
                        } else {
                            showNotification(messageNotification, data.error || '批量删除失败', 'error');
                        }
                    })
                    .catch(error => {
                        console.error('批量删除失败:', error);
                        showNotification(messageNotification, '批量删除留言时出错', 'error');
                    });
            }
        });


        // 加载文件列表
        function loadFileList() {
            fetch('/files')
                .then(response => response.json())
                .then(files => {
                    displayFileList(files);
                })
                .catch(error => {
                    console.error('获取文件列表失败:', error);
                    showNotification(uploadNotification, '加载文件列表失败', 'error');
                });
        }

        // 显示文件列表
        function displayFileList(files) {
            const container = document.getElementById('file-list');
            container.innerHTML = '';

            if (files.length === 0) {
                container.innerHTML = '<p>暂无文件</p>';
                return;
            }

            files.forEach(file => {
                const fileItem = document.createElement('div');
                fileItem.className = 'file-item';
                fileItem.title = file.name;

                // 格式化文件大小
                const sizeInKB = (file.size / 1024).toFixed(2);
                // 格式化日期
                const date = new Date(file.mtime).toLocaleString();

                fileItem.innerHTML = `
            <span class="file-name">${file.name}</span>
            <span class="file-size">${sizeInKB} KB</span>
            <span class="file-date">${date}</span>
        `;

                // 点击下载文件
                fileItem.addEventListener('click', () => {
                    window.open(file.path, '_blank');
                });

                container.appendChild(fileItem);
            });
        }

        // 页面加载时获取文件列表
        document.addEventListener('DOMContentLoaded', function () {
            loadMessages();
            loadFileList(); // 新增
        });
    </script>
</body>

</html>